<script setup>
import { ref, onMounted, reactive, computed } from 'vue'
import request from '@/utils/sj-request'
import { ROLES, ROLE_IDS } from '@/utils/permission'
import { usetikuUserStore } from '@/stores/sj-user'

const userStore = usetikuUserStore()

// 获取用户信息
const userInfo = computed(() => userStore.userInfo)

// 教师班级学科关联列表数据
const teacherClassesSubjectList = ref([])
// 搜索关键词
const searchKeyword = ref('')
// 选中的教师ID
const selectedTeacherId = ref('')
// 加载状态
const loading = ref(false)
// 分页参数
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 教师列表
const teacherList = ref([])
// 班级列表
const classesList = ref([])
// 学科列表
const subjectList = ref([])

// 对话框显示控制
const dialogVisible = ref(false)
const dialogTitle = ref('新增单位分配')

// 表单数据
const formData = reactive({
  id: null,
  teacherId: null,
  classesId: null,
  subjectId: null
})

// 表单校验规则
const rules = {
  teacherId: [
    { required: true, message: '请选择教师', trigger: 'change' }
  ],
  classesId: [
    { required: false, message: '请选择班级', trigger: 'change' }
  ],
  subjectId: [
    { required: true, message: '请选择学科', trigger: 'change' }
  ]
}

// 表单引用
const formRef = ref(null)

// 获取教师列表（仅教师和学科组长）
const fetchTeachers = async () => {
  try {
    const res = await request({
      url: '/user-management/list',
      method: 'get'
    })
    
    if (res.code === 200) {
      // 仅教师和学科组长
      teacherList.value = res.data.filter(user => user.roleId === ROLE_IDS.TEACHER || user.roleId === ROLE_IDS.SUBJECT_LEADER) || []
    } else {
      ElMessage.error(res.message || '获取教师列表失败')
    }
  } catch (error) {
    console.error('获取教师列表失败:', error)
    ElMessage.error('获取教师列表失败')
  }
}

// 获取班级列表
const fetchClasses = async () => {
  try {
    const res = await request({
      url: '/classes/all',
      method: 'get'
    })
    
    if (res.code === 200) {
      classesList.value = res.data || []
    } else {
      ElMessage.error(res.message || '获取班级列表失败')
    }
  } catch (error) {
    console.error('获取班级列表失败:', error)
    ElMessage.error('获取班级列表失败')
  }
}

// 获取学科列表
const fetchSubjects = async () => {
  try {
    const res = await request({
      url: '/subject/list',
      method: 'get'
    })
    
    if (res.code === 200) {
      subjectList.value = res.data || []
    } else {
      ElMessage.error(res.message || '获取学科列表失败')
    }
  } catch (error) {
    console.error('获取学科列表失败:', error)
    ElMessage.error('获取学科列表失败')
  }
}

// 获取教师班级学科关联列表
const fetchTeacherClassesSubjects = async () => {
  loading.value = true
  try {
    const res = await request({
      url: '/teacher-classes-subject/page',
      method: 'get',
      params: {
        page: pagination.value.currentPage,
        size: pagination.value.pageSize,
        teacherId: selectedTeacherId.value || null,
        keyword: searchKeyword.value
      }
    })
    
    if (res.code === 200) {
      // 添加序号字段
      teacherClassesSubjectList.value = res.data.records.map((item, index) => ({
        ...item,
        order: (pagination.value.currentPage - 1) * pagination.value.pageSize + index + 1
      })) || []
      pagination.value.total = res.data.total || 0
    } else {
      ElMessage.error(res.message || '获取单位分配列表失败')
    }
  } catch (error) {
    console.error('获取单位分配列表失败:', error)
    ElMessage.error('获取单位分配列表失败')
  } finally {
    loading.value = false
  }
}

// 处理页码变化
const handleCurrentChange = (page) => {
  pagination.value.currentPage = page
  fetchTeacherClassesSubjects()
}

// 处理每页条数变化
const handleSizeChange = (size) => {
  pagination.value.pageSize = size
  pagination.value.currentPage = 1
  fetchTeacherClassesSubjects()
}

// 处理搜索
const handleSearch = () => {
  pagination.value.currentPage = 1
  fetchTeacherClassesSubjects()
}

// 处理重置筛选条件
const handleReset = () => {
  searchKeyword.value = ''
  selectedTeacherId.value = ''
  pagination.value.currentPage = 1
  fetchTeacherClassesSubjects()
}

// 打开新增对话框
const handleAdd = () => {
  dialogTitle.value = '新增单位分配'
  // 重置表单
  formData.id = null
  formData.teacherId = null
  formData.classesId = null
  formData.subjectId = null
  
  // 显示对话框
  dialogVisible.value = true
}

// 打开编辑对话框
const handleEdit = (row) => {
  dialogTitle.value = '编辑单位分配'
  // 填充表单数据
  formData.id = row.id
  formData.teacherId = row.teacherId
  formData.classesId = row.classesId
  formData.subjectId = row.subjectId
  
  // 显示对话框
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const isEdit = formData.id !== null
        const url = '/teacher-classes-subject'
        const method = isEdit ? 'put' : 'post'
        
        const res = await request({
          url,
          method,
          data: formData
        })
        
        if (res.code === 200) {
          ElMessage.success(isEdit ? '编辑成功' : '新增成功')
          dialogVisible.value = false
          fetchTeacherClassesSubjects()
        } else {
          ElMessage.error(res.message || (isEdit ? '编辑失败' : '新增失败'))
        }
      } catch (error) {
        console.error(isEdit ? '编辑单位分配失败:' : '新增单位分配失败:', error)
        ElMessage.error(isEdit ? '编辑失败' : '新增失败')
      }
    }
  })
}

// 删除教师班级学科关联
const handleDelete = (id) => {
  ElMessageBox.confirm('确定要删除该单位分配吗？删除后不可恢复！', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await request({
        url: `/teacher-classes-subject/${id}`,
        method: 'delete'
      })
      
      if (res.code === 200) {
        ElMessage.success('删除成功')
        fetchTeacherClassesSubjects()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    } catch (error) {
      console.error('删除单位分配失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 组件挂载时获取数据
onMounted(() => {
  fetchTeachers()
  fetchClasses()
  fetchSubjects()
  fetchTeacherClassesSubjects()
})
</script>

<template>
  <div class="teacher-classes-subject-container">
    <!-- 搜索和筛选区域 -->
    <el-card class="filter-container" shadow="never">
      <el-form :inline="true" class="filter-form">
        <el-form-item label="关键词">
          <el-input
            v-model="searchKeyword"
            placeholder="请输入关键词搜索"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        
        <el-form-item 
        style="width: 15%;"
        label="教师">
          <el-select v-model="selectedTeacherId" placeholder="选择教师" clearable>
            <el-option
              v-for="teacher in teacherList"
              :key="teacher.id"
              :label="teacher.account"
              :value="teacher.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 列表区域 -->
    <el-card class="list-container" shadow="never">
      <template #header>
        <div class="card-header">
          <span>单位分配列表</span>
          <el-button type="primary" @click="handleAdd">新增单位分配</el-button>
        </div>
      </template>
      
      <el-table
        v-loading="loading"
        :data="teacherClassesSubjectList"
        border
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="80" align="center" />
        
        <el-table-column prop="teacherAccount" label="教师账户" width="150" />
        
        <el-table-column label="班级" width="150">
          <template #default="{ row }">
            {{ row.classesName ? row.classesName : '无' }}
          </template>
        </el-table-column>
        
        <el-table-column prop="subjectName" label="学科" width="150" />
        
        <el-table-column label="操作" width="180" align="center">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              size="small"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              link
              type="danger"
              size="small"
              @click="handleDelete(row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="教师账户" prop="teacherId">
          <el-select v-model="formData.teacherId" placeholder="请选择教师账户" style="width: 100%">
            <el-option
              v-for="teacher in teacherList"
              :key="teacher.id"
              :label="teacher.account"
              :value="teacher.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="班级" prop="classesId">
          <el-select v-model="formData.classesId" placeholder="请选择班级" style="width: 100%">
            <el-option
              v-for="classes in classesList"
              :key="classes.id"
              :label="classes.name"
              :value="classes.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="学科" prop="subjectId">
          <el-select v-model="formData.subjectId" placeholder="请选择学科" style="width: 100%">
            <el-option
              v-for="subject in subjectList"
              :key="subject.id"
              :label="subject.name"
              :value="subject.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.teacher-classes-subject-container {
  padding: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>